#!/usr/bin/env python3
"""
开发环境启动脚本

自动检查环境、配置和启动开发服务器
"""

import os
import sys
import subprocess
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    print("🐍 检查Python版本...")
    
    if sys.version_info < (3, 8):
        print("❌ 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    
    print(f"✅ Python版本: {sys.version}")
    return True

def check_dependencies():
    """检查依赖是否安装"""
    print("\n📦 检查依赖包...")
    
    required_packages = [
        "fastapi",
        "uvicorn",
        "sqlalchemy",
        "asyncpg",
        "redis",
        "pydantic",
        "pydantic-settings",
        "python-jose[cryptography]",
        "loguru",
        "httpx",
        "google-auth",
        "google-auth-oauthlib",
        "celery",
        "psutil"
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == "python-jose[cryptography]":
                __import__("jose")
            elif package == "google-auth-oauthlib":
                __import__("google_auth_oauthlib")
            elif package == "pydantic-settings":
                __import__("pydantic_settings")
            else:
                __import__(package.replace("-", "_"))
            print(f"  ✅ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"  ❌ {package}")
    
    if missing_packages:
        print(f"\n缺少依赖包，正在安装...")
        install_cmd = [sys.executable, "-m", "pip", "install"] + missing_packages
        try:
            subprocess.run(install_cmd, check=True)
            print("✅ 依赖包安装完成")
        except subprocess.CalledProcessError:
            print("❌ 依赖包安装失败，请手动运行:")
            print(f"pip install {' '.join(missing_packages)}")
            return False
    
    return True

def check_env_file():
    """检查环境配置文件"""
    print("\n⚙️ 检查环境配置...")
    
    env_file = Path(".env")
    env_example = Path(".env.example")
    
    if not env_file.exists():
        if env_example.exists():
            print("📋 复制环境配置模板...")
            import shutil
            shutil.copy(env_example, env_file)
            print("✅ 已创建.env文件，请根据需要修改配置")
        else:
            print("⚠️ 未找到.env文件，使用默认配置")
            create_default_env()
    else:
        print("✅ 环境配置文件存在")
    
    return True

def create_default_env():
    """创建默认环境配置"""
    env_content = """# YouTube订阅管理器环境配置

# 应用配置
DEBUG=true
HOST=127.0.0.1
PORT=5656

# 数据库配置
DB_HOST=localhost
DB_PORT=5432
DB_NAME=youtube_manager
DB_USER=postgres
DB_PASSWORD=
DATABASE_URL=

# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=
REDIS_URL=

# YouTube API配置（需要从Google Cloud Console获取）
YOUTUBE_API_KEY=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=http://localhost:5656/api/v1/auth/callback

# JWT配置
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# 日志配置
LOG_LEVEL=INFO

# 缓存配置
CACHE_PREFIX=youtube_manager
CACHE_DEFAULT_TTL=300

# 性能监控配置
PERFORMANCE_MONITORING_ENABLED=true
SLOW_QUERY_THRESHOLD=1.0

# 速率限制配置
RATE_LIMIT_ENABLED=true
DEFAULT_RATE_LIMIT=100
RATE_LIMIT_WINDOW=60
"""
    
    with open(".env", "w", encoding="utf-8") as f:
        f.write(env_content)
    
    print("✅ 已创建默认.env配置文件")

def check_services():
    """检查外部服务状态"""
    print("\n🔌 检查外部服务...")
    
    # 检查PostgreSQL连接
    try:
        import asyncpg
        print("  ℹ️ PostgreSQL驱动可用")
    except ImportError:
        print("  ❌ PostgreSQL驱动未安装")
        return False
    
    # 检查Redis连接
    try:
        import redis
        print("  ℹ️ Redis驱动可用")
    except ImportError:
        print("  ❌ Redis驱动未安装")
        return False
    
    print("  ⚠️ 请确保PostgreSQL和Redis服务正在运行")
    return True

def start_development_server():
    """启动开发服务器"""
    print("\n🚀 启动开发服务器...")
    
    try:
        # 设置环境变量
        env = os.environ.copy()
        env["PYTHONPATH"] = str(Path.cwd())
        
        # 启动uvicorn开发服务器
        cmd = [
            sys.executable, "-m", "uvicorn",
            "src.main:app",
            "--host", "127.0.0.1",
            "--port", "5656", 
            "--reload",
            "--log-level", "info"
        ]
        
        print(f"执行命令: {' '.join(cmd)}")
        print("📱 应用将在 http://127.0.0.1:5656 启动")
        print("📚 API文档: http://127.0.0.1:5656/docs")
        print("🔧 ReDoc文档: http://127.0.0.1:5656/redoc")
        print("\n按 Ctrl+C 停止服务器\n")
        
        subprocess.run(cmd, env=env)
        
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        return False
    
    return True

def main():
    """主函数"""
    print("🎯 YouTube订阅管理器开发环境启动")
    print("="*50)
    
    # 执行检查步骤
    if not check_python_version():
        sys.exit(1)
    
    if not check_dependencies():
        sys.exit(1)
    
    if not check_env_file():
        sys.exit(1)
    
    if not check_services():
        print("⚠️ 外部服务检查未通过，但可以继续启动")
    
    print("\n" + "="*50)
    print("✅ 环境检查完成，准备启动服务器...")
    
    # 询问是否继续
    try:
        response = input("\n是否启动开发服务器? (y/N): ").strip().lower()
        if response in ['y', 'yes', '是']:
            start_development_server()
        else:
            print("👋 取消启动")
    except KeyboardInterrupt:
        print("\n👋 用户取消")
        sys.exit(0)

if __name__ == "__main__":
    main()